<template>
  <view class="bg-layer"></view>
  <view class="container">
    <!-- 头部 -->
    <view class="header glassmorphism">
      <text class="title">错题本</text>
      <text class="points">
        <uni-icons type="coin" size="18" color="#FF9800" />
        积分：{{ user.points || 0 }}
      </text>
    </view>

    <!-- 错题列表 -->
    <scroll-view scroll-y class="wrong-list">
      <view v-if="loading" class="loading">
        <view class="spinner"></view>
        <text>加载中...</text>
      </view>
      <view v-else-if="!wrongQuestions.length" class="empty">
        <uni-icons type="info" size="24" color="#666" />
        <text>暂无错题</text>
      </view>
      <view v-else v-for="(question, index) in wrongQuestions" :key="question._id" class="wrong-card glassmorphism"
        @touchstart="cardScale(index, true)" @touchend="cardScale(index, false)">
        <text class="question-title">{{ index + 1 }}. {{ question.content }}</text>
        <view class="options">
          <view v-for="(value, key) in question.options" :key="key" class="option">
            <text :class="{ 'correct': key === question.correct_answer, 'wrong': key === question.user_answer && key !== question.correct_answer }">
              {{ key }}. {{ value }}
            </text>
          </view>
        </view>
        <view class="explanation">
          <uni-icons type="bulb" size="16" color="#FF9800" />
          <text>解析：{{ question.explanation }}</text>
        </view>
        <view class="resubmit-section">
          <radio-group @change="selectResubmitAnswer($event, index)" class="resubmit-options">
            <label v-for="(value, key) in question.options" :key="key" class="resubmit-option">
              <radio :value="key" :checked="resubmitAnswers[index] === key" />
              <text>{{ key }}</text>
            </label>
          </radio-group>
          <button class="resubmit-button" :disabled="!resubmitAnswers[index]" @click="resubmit(index, question._id)">重新提交</button>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      user: {},
      wrongQuestions: [],
      resubmitAnswers: [],
      loading: false
    };
  },
  onLoad() {
    this.loadUserData();
    this.loadWrongQuestions();
  },
  onShow() {
    this.getUserPoints();
  },
  methods: {
    loadUserData() {
      this.user = uni.getStorageSync('user') || {};
      if (!this.user.id) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        uni.navigateTo({ url: '/pages/student/login' });
      }
    },
    async getUserPoints() {
      try {
        const res = await uniCloud.callFunction({
          name: 'getUserPoints',
          data: { user_id: this.user.id }
        });
        if (res.result.code === 0) {
          this.user.points = res.result.data.points;
          uni.setStorageSync('user', this.user);
        }
      } catch (e) {
        console.error('获取积分失败:', e);
        uni.showToast({ title: '获取积分失败', icon: 'none' });
      }
    },
    async loadWrongQuestions() {
      this.loading = true;
      try {
        const res = await uniCloud.callFunction({
          name: 'getWrongQuestions',
          data: { user_id: this.user.id }
        });
        if (res.result.code === 0) {
          this.wrongQuestions = res.result.data;
          this.resubmitAnswers = new Array(this.wrongQuestions.length).fill('');
        } else {
          uni.showToast({ title: res.result.msg || '加载错题失败', icon: 'none' });
        }
      } catch (e) {
        console.error('加载错题失败:', e);
        uni.showToast({ title: '加载错题失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },
    selectResubmitAnswer(e, index) {
      this.$set(this.resubmitAnswers, index, e.detail.value);
    },
    async resubmit(index, wrong_question_id) {
      const answer = this.resubmitAnswers[index];
      if (!answer) {
        uni.showToast({ title: '请选择答案', icon: 'none' });
        return;
      }
      try {
        const res = await uniCloud.callFunction({
          name: 'resubmitWrongQuestion',
          data: { user_id: this.user.id, wrong_question_id, user_answer: answer }
        });
        if (res.result.code === 0) {
          uni.showToast({
            title: res.result.msg || '提交成功',
            icon: res.result.data.points > 0 ? 'success' : 'none'
          });
          this.user.points = res.result.data.totalPoints || this.user.points;
          uni.setStorageSync('user', this.user);
          this.$set(this.resubmitAnswers, index, ''); // 清空选择
          this.loadWrongQuestions(); // 刷新错题列表
        } else {
          uni.showToast({ title: res.result.msg || '重新提交失败', icon: 'none' });
        }
      } catch (e) {
        console.error('重新提交失败:', e);
        uni.showToast({ title: '重新提交失败', icon: 'none' });
      }
    },
    cardScale(index, isTouch) {
      this.animate(`.wrong-card:nth-child(${index + 1})`, [
        { transform: `scale(${isTouch ? 0.98 : 1})` }
      ], 200);
    },
    animate(selector, keyframes, duration) {
      const query = uni.createSelectorQuery().in(this);
      query.select(selector).boundingClientRect();
      query.exec(res => {
        if (res[0]) {
          res[0].animate(keyframes, {
            duration,
            fill: 'forwards'
          });
        }
      });
    }
  }
};
</script>

<style scoped>
/* 全局样式 */
.bg-layer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 40vh;
  background: linear-gradient(135deg, #4a90e2 0%, #5aa1ff 100%);
  z-index: 0;
  border-radius: 0 0 20% 20%;
}

.container {
  position: relative;
  padding: 20px;
  min-height: 100vh;
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 玻璃态效果 */
.glassmorphism {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.05);
}

/* 头部 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-radius: 16px;
  margin-bottom: 20px;
  width: 100%;
}

.title {
  font-size: 20px;
  font-weight: 700;
  color: #333;
}

.points {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  background: rgba(255, 152, 0, 0.2);
  padding: 6px 12px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 错题列表 */
.wrong-list {
  height: calc(100vh - 140px);
  width: 100%;
  max-width: 600px;
}

.wrong-card {
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 16px;
  transition: transform 0.3s;
  animation: cardEnter 0.6s cubic-bezier(0.23, 1, 0.32, 1);
}

.question-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  line-height: 1.5;
}

.options {
  margin-bottom: 12px;
}

.option {
  font-size: 14px;
  padding: 6px 0;
}

.correct {
  color: #4CAF50;
  font-weight: 500;
}

.wrong {
  color: #F44336;
  font-weight: 500;
}

.explanation {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  background: rgba(255, 152, 0, 0.05);
  border-radius: 8px;
  margin-bottom: 12px;
  gap: 8px;
}

.explanation text {
  font-size: 14px;
  color: #FF9800;
  flex: 1;
}

.resubmit-section {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.resubmit-options {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
}

.resubmit-option {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  transition: background 0.2s;
}

.resubmit-option radio {
  margin-right: 8px;
}

.resubmit-option:hover {
  background: rgba(74, 144, 226, 0.1);
}

.resubmit-button {
  background: linear-gradient(45deg, #4a90e2, #5aa1ff);
  color: white;
  border-radius: 12px;
  padding: 10px 20px;
  font-size: 14px;
  font-weight: 500;
  border: none;
  transition: transform 0.2s, box-shadow 0.2s;
}

.resubmit-button[disabled] {
  background: #e0e0e0;
  color: #9e9e9e;
  box-shadow: none;
}

.resubmit-button:active {
  transform: scale(0.95);
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #666;
  padding: 24px;
}

.spinner {
  width: 24px;
  height: 24px;
  border: 3px solid rgba(74, 144, 226, 0.3);
  border-radius: 50%;
  border-top-color: #4a90e2;
  animation: spin 1s linear infinite;
  margin-bottom: 8px;
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #666;
  padding: 24px;
  gap: 8px;
}

/* 动画 */
@keyframes cardEnter {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>